package day4;

import org.w3c.dom.Node;

import java.util.HashMap;

public class ch3 {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    //25
    public ListNode reverseKGroup(ListNode head, int k) {

        ListNode n = head;
        int len = 0;
        while (n!=null){
            n = n.next;
            len++;
        }
        int num = len/k;



        ListNode tep= new ListNode(0);
        tep.next = head;
        ListNode[] arr=fun(tep,k);
        ListNode res = arr[0].next;
        for (int i = 1; i < num; i++) {
            arr= fun(arr[1],k);
        }

        return res;




    }

    public ListNode[] fun(ListNode head,int k){
        ListNode node = head.next;
        ListNode end = node;
        for (int i = 0; i <k; i++) {
            end = end.next;
        }

        head.next = end;
        ListNode cal = node;
        for (int i = 0; i < k; i++) {
            ListNode next = node.next;

            node.next = head.next;
            head.next = node;
            node = next;
        }

        return new ListNode[]{head,cal};
    }


    //138
    public Node copyRandomList(Node head) {
        HashMap<Node,Node> map = new HashMap<>();
        int num = 0;
        Node n = head;
        while (n!=null){
            Node tep = new Node(n.val);
            map.put(n,tep);
            num++;
            n = n.next;
        }

        int index = 0;
        Node p = head;
        while (p!=null){
            if(p.next!=null){
                map.get(p).next = map.get(p.next);
            }
            if(p.random!=null){
                map.get(p).random = map.get(p.random);
            }
            p = p.next;
        }


        return map.get(head);


    }

}
